<template>
  <mars-dialog
    title="站点详情"
    custom-class="zhyq-dialog zpdetail-company-box"
    closeable
    v-bind="attrs"
    @resize="resize"
    width="100vw"
    :position="{ top: 80, bottom: 100, left: '22.5%' }"
  >
    <div class="company">
      <div @click="comeOutClick" class="notification">
        <div @click.stop="childClicked" class="center-div">
          <div class="deConent">
            <div v-if="showConent" class="conentList">
              <div @scroll="handleScroll" class="leftScoll">
                <div
                  v-for="(device) in abnormalDeviceList"
                  :key="device.id"
                  @click="deviceClick(device)"
                  :class="[device.active ? 'leftTextConent' : '']"
                  class="leftConent"
                >
                  <div class="single-line">车牌：{{ device.plateNumber }}</div>
                  <div class="single-line">噪声：<span v-if="device.leqRtd">{{ device.leqRtd }} dB</span></div>
                  <div class="single-line">时间：{{ device.occurTime }}</div>
                </div>
              </div>
              <div class="rightConent">
                <div class="rightTopConent">
                  <div class="rightTopImgConent">
                    <ImagePreview v-if="imageUrl" class="deviceImg" :src="imageUrl" :preview-src-list="[imageUrl]" />
                  </div>
                  <div class="rightTopInfoConent">
                    <div class="info">
                      <div class="item"><span class="item-label">车牌号：</span><span class="item-value">{{ detailConent?.plateNumber || "--" }}</span></div>
                      <div class="item"><span class="item-label">噪声：</span><span class="item-value" v-if="detailConent.leqRtd">{{ detailConent?.leqRtd || "--" }} dB</span></div>
                      <div class="item"><span class="item-label">车辆类型：</span><span class="item-value">{{ detailConent?.plateType || "--" }}</span></div>
                      <div class="item"><span class="item-label">阈值：</span><span class="item-value">{{ detailConent?.threshold || "--" }} dB</span></div>
                      <div class="item"><span class="item-label">状态：</span><span class="item-value">告警中</span></div>
                      <div class="item"><span class="item-label">超限时间：</span><span class="item-value">{{ detailConent?.occurTime || "--" }}</span></div>
                      <div class="item"><span class="item-label">抓拍设备：</span><span class="item-value">{{ detailConent?.deviceName || "--" }}</span></div>
                    </div>
                  </div>
                </div>

                <div class="myTypeVideo">
                  <video v-if="videoUrl" id="myVideo" class="supportvideoUrl" controls>
                    <source :src="videoUrl" type="video/mp4" />
                    Your browser does not support the video tag.
                  </video>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </mars-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, useAttrs, onUnmounted, computed } from "vue"
import { useWidget } from "@mars/common/store/widget"
import { getCapture, listByIds } from "@mars/api/data/index"
import ImagePreview from "@mars/components/ImagePreview/index.vue"

const attrs = useAttrs()
const { currentWidget } = useWidget()

let myChart1: any
function initPannel(item: any) {}

function resize() {
  if (myChart1) {
    myChart1.resize()
  }
}

const propsEmit = defineEmits(["hideAbnormalDevice"])

const showLegend = ref(false)
const showConent = ref(false)
const abnormalDeviceTitle = ref("")
const abnormalDeviceList = ref([])

const paramCode = ref()
const pageNum = ref(1)

onMounted(() => {
  paramCode.value = currentWidget.data.details.code
  pageNum.value = 1
  abnormalDeviceList.value = []
  getCaptureList(currentWidget.data.details.code, "1")
 // 监听滚动事件
 document.addEventListener("scroll", handleScroll)
})

onUnmounted(() => {
  // 移除滚动事件监听
  document.removeEventListener("scroll", handleScroll)
})

const comeOutClick = () => {
  showLegend.value = false
  pageNum.value = 1
  propsEmit("hideAbnormalDevice")
}

const childClicked = (event) => {
    // 使用 .stop 修饰符阻止事件冒泡
    event.stopPropagation()
}

const detailConent = ref<any>({})

// 获取抓拍列表
const getCaptureList = (code, str) => {
  // console.log("code===", code)
  showLegend.value = false
  showConent.value = false
  getCapture({ deviceCode: code, pageSize: 20, pageNum: pageNum.value }).then((res:any) => {
    showLegend.value = true
    showConent.value = true
    // console.log("抓拍:======", JSON.stringify(res))

    for (let i = 0; i < res.rows.length; i++) {
      res.rows[i].active = false
    }

    abnormalDeviceList.value = [...abnormalDeviceList.value, ...res.rows]
    abnormalDeviceList.value = filterDuplicateObjects(abnormalDeviceList.value, "id")

    if (str === "1") {
      abnormalDeviceList.value[0].active = true
      detailConent.value = abnormalDeviceList.value[0]
      getImageUrl(abnormalDeviceList.value[0].imgUrl)
      getWaveUrl(abnormalDeviceList.value[0].waveUrl)
      abnormalDeviceTitle.value = abnormalDeviceList.value[0].deviceCode
      detailConent.value = abnormalDeviceList.value[0]
    }

  }).catch(() => {
    showConent.value = false
  })
}

const handleScroll = (event) => {
  const container = event.target
  // 容器总高度 - 滚动位置 - 容器可视区域高度
  if (container.scrollHeight - container.scrollTop <= container.clientHeight) {
    // console.log("滑动到底了！")
     // 触发方法
    onScrollToBottom()
  }
}

const onScrollToBottom = () => {
  // console.log('滚动到了底部！');
  // // 执行其他逻辑
  pageNum.value++
  getCapturePagingList(paramCode.value, "1")
}

// 获取抓拍列表
const getCapturePagingList = (code, str) => {

  getCapture({ deviceCode: code, pageSize: 20, pageNum: pageNum.value }).then((res:any) => {

    showConent.value = true
    // console.log('抓拍:======',JSON.stringify(res))
    for (let i = 0; i < res.rows.length; i++) {
      res.rows[i].active = false
    }
    abnormalDeviceList.value = [...abnormalDeviceList.value, ...res.rows]
    abnormalDeviceList.value = filterDuplicateObjects(abnormalDeviceList.value, "id")

    if (str === "1") {
      abnormalDeviceList.value[0].active = true
      detailConent.value = abnormalDeviceList.value[0]
      getImageUrl(abnormalDeviceList.value[0].imgUrl)
      getWaveUrl(abnormalDeviceList.value[0].waveUrl)
      abnormalDeviceTitle.value = abnormalDeviceList.value[0].deviceCode
      detailConent.value = abnormalDeviceList.value[0]
    }

  }).catch(() => {
    showConent.value = false
  })
}


const filterDuplicateObjects = (arr, key) => {
    const map = new Map()
    return arr.filter((item) => {
        const keyValue = item[key]
        return map.has(keyValue) ? false : map.set(keyValue, item)
    })
  }


const imageUrl = ref("")
const getImageUrl = (imgId) => {
  if (imgId) {
    listByIds(imgId).then((res) => {
      console.log("图片:", res)
      imageUrl.value = res.data[0].url
    })
  }
}

const videoUrl = ref("")
const getWaveUrl = (waveId) => {
  videoUrl.value = ""
  if (waveId) {
    listByIds(waveId).then((res) => {
        // console.log('视频:',res)
        videoUrl.value = res.data[0].url
      })
  }
}


const deviceClick = (device) => {

  detailConent.value = {}

  for (let i = 0; i < abnormalDeviceList.value.length; i++) {
    abnormalDeviceList.value[i].active = false
  }
    device.active = true
    getImageUrl(device.imgUrl)
    getWaveUrl(device.waveUrl)

    // console.log('抓拍设备====',device)

    detailConent.value = device
}

</script>


<style lang="less">
.zpdetail-company-box {
  width: 55vw;
  height: 80vh;
  min-width: 930px;
  min-height: 620px;
  .pannel-model__header {
    background: none;
    height: 320px;
  }
}
.company {
  height: 100%;
  width: 100%;
  overflow: hidden;
  display: flex;
}
.notification{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.center-div {
  color: #ffffff;
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
  border-radius: 30px;
}
.deConent{
  width: 100%;
  height: 100%;
}
.conentList{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.leftScoll{
  width: 38%;
  height: 100%;
  overflow-x: hidden; /*x轴禁止滚动*/
  overflow-y: scroll; /*y轴滚动*/
}
.leftScoll::-webkit-scrollbar {
  display: none; /*隐藏滚动条*/
}
.leftConent{
  width: 100%;
  height: 9vh;
  background: url(  '@mars/assets/service/deviceAlarm.png'   ) no-repeat;
  background-size: 100% 100%;
  padding: 1.5vh 0 1vh 1vw;
  cursor: pointer;
}
.leftTextConent{
  color: #f08282;
}
.single-line {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis; /* 可选，当需要显示省略号表示文本被截断时使用 */
}

.rightConent{
  width: 100%;
  height: 100%;
  padding: 20px;
}
.rightTopConent{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 20%;
}
.rightTopImgConent{
  width: 28%;
  .deviceImg{
    width: 100%;
    height: 100%;
  }
}
.rightTopInfoConent{
  width: 68%;
  .info {
    display: grid;
    grid-template-columns: 50% 50%; /* 2 columns */
    gap: 8px; /* spacing between items */
    .item {
      display: flex;
      justify-content: left;
      border-radius: 4px;
    }
  }
}
.myTypeVideo{
  height: 80%;
  .supportvideoUrl{
    width: 100%;
    height: 100%;
  }
}
</style>
